<template>
	<div class="scanCode-container">
		<el-card shadow="hover"
			:body-style="{ padding: '5px 5px 0 5px', display: 'flex', width: '100%', height: '100%', alignItems: 'start' }">
			<el-form :model="state.queryParams" ref="queryForm" :show-message="false" :inlineMessage="true" label-width="auto"
				style="flex: 1 1 0%" @submit.prevent="">
				<el-row :gutter="10">
					<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6" class="mb5">
						<el-form-item label="型号" prop="modelNumber">
							<el-select v-model="state.queryParams.modelNumber" filterable placeholder="请选择型号" clearable
								@change="modelChange">
								<el-option v-for="(item, index) in codeList" :key="index" :value="item.id"
									:label="`${item.modelNumber}`" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6" class="mb5">
						<el-form-item label="69码" prop="code69">
							<el-input v-model="state.queryParams.code69" placeholder="69码" readonly />
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
		</el-card>
		<el-card class="full-table" shadow="hover" style="margin-top: 5px;background-color: transparent;">
			<el-row style="height: 100%;">
				<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" style="padding-right: 10px;">
					<div style="background-color: #fff;border-radius: 5px;height: 100%;padding: 5px;">
						<el-row>
							<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6" class="mb5">
								<el-form-item label="打印服务状态" prop="opend">
									<el-tag v-if="state.opened" type="success">已连接</el-tag>
									<el-tag v-else type="danger">未连接</el-tag>
								</el-form-item>
							</el-col>
							<el-col :xs="24" :sm="18" :md="18" :lg="18" :xl="18" class="mb5">
								<el-form-item label="打印机列表" prop="printers">
									<el-select v-model="state.printer" filterable placeholder="请选择打印机" clearable>
										<el-option v-for="(item, index) in state.printList" :key="index" :value="item.name"
											:label="`${item.name}`" />
									</el-select>
								</el-form-item>
							</el-col>
						</el-row>

						<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb5">
							<el-input v-model="state.queryParams.code" placeholder="请在这里扫条码" clearable
								@keyup.enter.native="handleQuery"></el-input>
						</el-col>
					</div>
				</el-col>
				<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
					<div style="background-color: #fff;border-radius: 5px;height: 100%;display: flex;padding: 10px;">
						<div class="prevViewDiv"></div>
					</div>
				</el-col>
			</el-row>
		</el-card>
	</div>
</template>

<script lang="ts" setup name="scanCode">
import { onMounted, reactive, ref, nextTick } from 'vue';
import { ElMessageBox, ElMessage, ElNotification } from "element-plus";
import { auth } from '/@/utils/authFunction';
import { FullScreen } from '@element-plus/icons-vue'
import { VxeGridInstance, VxeGridListeners, VxeGridPropTypes } from 'vxe-table';
import { useVxeTable } from '/@/hooks/useVxeTableOptionsHook';
import { Local } from '/@/utils/storage';
import { hiprint } from 'vue-plugin-hiprint';
import { formatDate } from '/@/utils/formatTime';
import { TaskRunner } from 'concurrent-tasks';

// 子窗口
import PrintDialog from '/@/views/system/print/component/hiprint/preview.vue';
import EditDialog from '/@/views/dashboard/baseCode/component/editDialog.vue';
import ModifyRecord from '/@/components/table/modifyRecord.vue';

import { listBaseCode, pageBaseCode } from '/@/api/dashboard/baseCode';
import { detailPrintDev } from '/@/api/system/printDev';

// 子窗口对象
const xGrid = ref<VxeGridInstance>();

const codeList = ref<any>([]);
const checked = ref<boolean>();

// 变量
const state = reactive({
	opened: false,
	hiprintTemplate: {} as any,
	printData: [] as any,
	// 查询参数
	queryParams: {
		searchKey: undefined,
		modelNumber: undefined,
		code69: undefined,
		code: undefined,
		printTemplateId: undefined
	},
	localPageParam: {
		pageSize: 50 as number,
		defaultSort: { field: 'createTime', order: 'asc', descStr: 'desc' },
	},
	printer: '',
	printList: [] as any,
	modelNumber: undefined,
	visible: false,
	title: '',
	printTemp: {} as any
});

// 本地存储参数
const localPageParamKey = 'localPageParam:scanCode';

const getCodeList = async () => {
	let list = await listBaseCode();
	codeList.value = list.data.result ?? [];
};

const modelChange = async (val: any) => {
	state.printData = []
	let code69 = codeList.value.find((item: any) => item.id == val)?.code69;
	let tempId = codeList.value.find((item: any) => item.id == val)?.printTemplateId;
	state.queryParams.code69 = code69;
	state.printTemp = (await detailPrintDev(tempId)).data.result.printTemplate;
	state.modelNumber = codeList.value.find((item: any) => item.id == val)?.modelNumber;
	state.queryParams.printTemplateId = tempId;
	// console.log(state.printTemp);
	state.hiprintTemplate = new hiprint.PrintTemplate({
		template: JSON.parse(state.printTemp),
	});
	let data = {
		'型号': state.modelNumber,
		'69码': state.queryParams.code69,
		'code': undefined
	}
	state.printData.push(data)
};

// 查询操作
const handleQuery = async (reset = false) => {
	nextTick(() => {
		state.printData[0].code = state.queryParams.code
		// console.log('state.printData', state.printData)
		$('.prevViewDiv').html(state.hiprintTemplate.getHtml(state.printData))
		$('.hiprint-printPaper').css('margin', '10px auto');
		$('.hiprint-printPaper').css('border-radius', '5px');
		$('.hiprint-printPaper').css('box-shadow', '0 2px 12px 0 rgba(0, 0, 0, 0.1)');
		if (window.hiwebSocket.opened) {
			tasksPrint()
			state.queryParams.code = undefined
		} else {
			ElMessageBox.alert(
				`<div>
            连接【${hiwebSocket.host}】失败！
            <br />
            请确保目标服务器已
            <a
              href="https://gitee.com/CcSimple/electron-hiprint/releases"
              target="_blank"
            >
              下载
            </a>
            并
            <a href="hiprint://" target="_blank">
              运行
            </a>
            打印服务！
          </div>`,
				'提示',
				{
					dangerouslyUseHTMLString: true,
				}
			)
		}
	})
};

const tasksPrint = async () => {
	const runner = new TaskRunner();
	runner.setConcurrency(1); // 同时执行数量
	console.log(runner);
	const task = [];
	const tasksKey = `open${Date.now()}`;

	// 假设你需要添加的任务数量
	for (let i = 1; i <= 1; i++) { // 这里我改为循环5次，根据你的需要调整
		let key = `task${i}`;
		// 使用箭头函数确保 this 上下文
		task.push((done) => {
			realPrint(runner, done, key, i, state.printData, tasksKey);
		});
	}
	runner.addMultiple(task);
	runner.start()

	// openNotification(runner, tasksKey);
};

function realPrint(runner, done, key, i, printData, tasksKey) {
	console.log(key, i, printData);
	const not = ElNotification({
		key: key,
		title: `正在准备打印第 ${i} 张`,
		message: '队列运行中...',
		type: 'info'
	});

	// 假设 state.hiprintTemplate 是正确的初始化方式
	state.hiprintTemplate = new hiprint.PrintTemplate({
		template: JSON.parse(state.printTemp),
	});

	state.hiprintTemplate.print2(printData, { printer: state.printer, title: key })
	state.hiprintTemplate.on('printSuccess', function () {
		console.log(runner)
		let info = runner.tasks.pending.length > 1 ? '准备打印下一张' : '已完成打印'
		done()
		if (!runner.busy) {
			// ElNotification.closeAll();
		}
		ElNotification({
			key: key,
			title: key + ' 打印成功',
			message: info,
			type: 'success'
		});
	})
	state.hiprintTemplate.on('printError', function () {
		not.close()
		done()
		ElMessage.error('打印失败，已加入重试队列中')
		runner.add(realPrint(runner, done, key, i, printData))
	})
}
// 页面初始化
onMounted(async () => {
	getCodeList();
	hiprint.init()
	hiprint.hiwebSocket.setHost("http://localhost:17521")
	setTimeout(() => {
		// console.log('hiprint.hiwebSocket.opened', hiprint.hiwebSocket.opened)
		if (!hiprint.hiwebSocket.opened) {
			ElMessageBox.alert(
				`<div>
            连接【${hiprint.hiwebSocket.host}】失败！
            <br />
            请确保目标服务器已
            <a
              href="https://gitee.com/CcSimple/electron-hiprint/releases"
              target="_blank"
            >
              下载
            </a>
            并
            <a href="hiprint://" target="_blank">
              运行
            </a>
            打印服务！
						<br />
						运行后请手动刷新页面！
          </div>`,
				'提示',
				{
					dangerouslyUseHTMLString: true,
				}
			)
		} else {
			state.opened = true;
			state.printList = hiprint.hiwebSocket.getPrinterList();
			console.log(state.printList);
			state.printList.forEach((el: any) => {
				if (el.isDefault) state.printer = el.name
			});
		}
	}, 500);
});



</script>

<style lang="scss" scoped>
:deep(.el-input),
:deep(.el-select),
:deep(.el-input-number) {
	width: 100%;
}
</style>
